package com.shanpin.shebao.web.module.ent;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.shanpin.core.http.JsonView;
import com.shanpin.core.utils.JsonUtil;
import com.shanpin.shebao.model.ServiceResult;

@Controller
@RequestMapping("/ent")
public class EnterpriseController {

	@Autowired
	private EnterpriseService enterpriseService;
	
	@RequestMapping("/to")
	public ModelAndView toEnt() {
		ModelAndView mav = new ModelAndView("enterprise");
		return mav;
	}
	

	/**
	 * 企业信息登记
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/sign")
	public void sign(EntParam p, HttpServletResponse resp) throws IOException {
		String msg = null;
		if (StringUtils.isBlank(p.getEnName()) 
				|| StringUtils.isBlank(p.getContactName())
				|| StringUtils.isBlank(p.getContactPhone())
				|| StringUtils.isBlank(p.getCity())
				|| StringUtils.isBlank(p.getDemand()) ) {
			msg = "公司名、联系人、电话、城市、业务要求填写。";
		}
		if (StringUtils.isNotBlank(msg)) {
			JsonView.fail(msg).write(resp);
			return;
		}
		ServiceResult<Void> sr = enterpriseService.sign(p);
		if (StringUtil.isNotBlank(sr.msg)) {
			JsonView.fail(sr.msg).write(resp);
			return;
		}
		JsonView.ok().write(resp);
	}
	
	/**
	 * 企业信息登记(跨域)
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/cros/sign")
	public void crosSign(EntParam p, HttpServletResponse resp) throws IOException {
		resp.setContentType("application/json;charset=utf-8");
		PrintWriter pw = resp.getWriter();
		String msg = null;
		if (StringUtils.isBlank(p.getEnName()) 
				|| StringUtils.isBlank(p.getContactName())
				|| StringUtils.isBlank(p.getContactPhone())
				|| StringUtils.isBlank(p.getCity())
				|| StringUtils.isBlank(p.getDemand()) ) {
			msg = "公司名、联系人、电话、城市、业务要求填写。";
		}
		if (StringUtils.isNotBlank(msg)) {
			pw.write("enRegisterCallback('"+JsonUtil.toStr(JsonView.fail(msg))+"')");
			return;
		}
		ServiceResult<Void> sr = enterpriseService.sign(p);
		if (StringUtil.isNotBlank(sr.msg)) {
			pw.write("enRegisterCallback('"+JsonUtil.toStr(JsonView.fail(sr.msg))+"')");
			return;
		}
		
		pw.write("enRegisterCallback('"+JsonUtil.toStr(JsonView.ok())+"')");
		pw.flush();
	}
}
